<template>
  <div class="add-role">
    <header class="add-header">
      <div class="left">
        <span class="arrow" @click="$router.back()"><i class="el-icon-arrow-left" />返回</span>
        <span>|</span>
        <span>{{ roleId ? '编辑角色' : '添加角色' }}</span>
      </div>
      <div class="right">
        后台管理员
      </div>
    </header>
    <main class="add-main">
      <div class="step-container">
        <el-steps direction="vertical" :active="activeStep">
          <el-step title="角色信息" />
          <el-step title="权限信息" />
          <el-step title="检查并完成" />
        </el-steps>
      </div>
      <div v-show="activeStep===1" class="form-container">
        <div class="title">角色信息</div>
        <div class="form">
          <el-form ref="roleForm" class="form-box" :model="roleForm" :rules="roleRules">
            <el-form-item label="角色名称" prop="roleName">
              <el-input v-model="roleForm.roleName" />
            </el-form-item>
            <el-form-item label="角色描述" prop="remark">
              <el-input v-model="roleForm.remark" />
            </el-form-item>
          </el-form>
        </div>
      </div>
      <div v-show="activeStep===2" class="form-container">
        <div class="title">权限配置</div>
        <div class="tree-wrapper">
          <div v-for="item in treeList" :key="item.id" class="tree-item">
            <div class="tree-title"> {{ item.title }} </div>
            <!-- show-checkbox 展示复选框 -->
            <!-- default-expand-all默认展开 -->
            <!-- check-strictly 接触复选框父子级的关联关系 让角色只拥有观看权限，没有修改权限-->
            <el-tree
              ref="tree"
              :data="item.children"
              :props="defaultProps"
              show-checkbox
              check-strictly
              default-expand-all
              :highlight-current="false"
              node-key="id"
            />
          </div>
        </div>
      </div>
      <div v-show="activeStep===3" class="form-container">
        <div class="title">检查并完成</div>
        <div class="form">
          <div class="info">
            <div class="form-item">角色名称：{{ roleForm.roleName }}</div>
            <div class="form-item">角色描述：{{ roleForm.remark }}</div>
            <div class="form-item">角色权限：</div>
            <div class="tree-wrapper">
              <div v-for="item in disabledList" :key="item.id" class="tree-item">
                <div class="tree-title">{{ item.title }}</div>
                <el-tree
                  ref="disabledTree"
                  :data="item.children"
                  show-checkbox
                  check-strictly
                  default-expand-all
                  node-key="id"
                  :props="{ label: 'title'}"
                />
              </div>
            </div>
          </div>
        </div>
      </div>
    </main>
    <footer class="add-footer">
      <div class="btn-container">
        <el-button v-if="activeStep > 1" @click="prevStep">上一步</el-button>
        <el-button v-if="activeStep < 3" type="primary" @click="nextStep">下一步</el-button>
        <el-button v-if="activeStep === 3" type="primary" @click="confirmAdd">{{ roleId ?'确定编辑' : '确定添加' }}</el-button>
      </div>
    </footer>
  </div>
</template>

<script>
import { getTreeListAPI, createRoleUserAPI, getRoleDetailAPI, updateRoleAPI } from '@/api/system'
export default {
  data() {
    return {
      activeStep: 1,
      roleForm: {
        roleName: '',
        remark: '',
        perms: []
      },
      roleRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ],
        remark: [
          { required: true, message: '请输入角色描述', trigger: 'blur' }
        ]
      },
      treeList: [],
      defaultProps: {
        label: 'title'
      },
      disabledList: []
    }
  },
  computed: {
    roleId() {
      return this.$route.query.id
    }
  },
  async created() {
    // 必须保证数据先渲染出来之后，再进行其他获取数据定操作
    await this.getTreeList()
    if (this.roleId) {
      this.getRoleDetail()
      // console.log('回填编辑数据执行', this.$route.query.id)
    }
  },
  methods: {
    // 下一步操作
    nextStep() {
      if (this.activeStep === 3) return
      if (this.activeStep === 1) {
        // 进入下一页之前，要进行校验是否填写了表单
        this.$refs.roleForm.validate(flag => {
          if (flag) {
            return this.activeStep++
          }
        })
      } else if (this.activeStep === 2) {
        // console.log(this.roleId)

        // 进行校验，看用户是否勾选了一些数据
        const treeComponentList = this.$refs.tree
        console.log(treeComponentList)

        this.roleForm.perms = []
        treeComponentList.forEach(tree => {
          this.roleForm.perms.push(tree.getCheckedKeys())
        })
        // 如果长度为零 没有选中任何东西
        if (this.roleForm.perms.flat().length <= 0) {
          this.$message.warning('请至少勾选一个权限点')
          return
        }
        const disabledTreeList = this.$refs.disabledTree
        // console.log(disabledTreeList)

        // 回填已经选择的数据
        disabledTreeList.forEach((item, index) => {
          item.setCheckedKeys(this.roleForm.perms[index])
        })
        // 进入到下一页
        this.activeStep++
      }
    },
    // 上一步操作
    prevStep() {
      if (this.activeStep === 2 || this.activeStep === 3) {
        return this.activeStep--
      }
    },
    // 获取所有的权限列表
    async getTreeList() {
      const res = await getTreeListAPI()
      this.treeList = res.data
      this.disabledList = JSON.parse(JSON.stringify(res.data))
      // 处理禁用
      this.addDisabled(this.disabledList)
    },
    // 处理禁用函数
    addDisabled(disabledList) {
      disabledList.forEach(item => {
        item.disabled = true
        // 递归处理
        if (item.children && item.children.length > 0) {
          this.addDisabled(item.children)
        }
      })
    },
    // 确认提交，创建角色
    async confirmAdd() {
      // 编辑角色信息
      if (this.roleId) {
        // 删除多余数据
        delete this.roleForm.userTotal
        await updateRoleAPI(this.roleForm)
      } else {
        await createRoleUserAPI(
          this.roleForm
        )
      }
      this.$message({
        type: 'success',
        message: `${this.roleId ? '编辑' : '添加'}角色成功`
      })
      this.$router.back()
    },
    // 回填编辑表单中的数据
    async getRoleDetail() {
      const res = await getRoleDetailAPI(this.roleId)
      this.roleForm = res.data
      // 回填基础表单
      // console.log(res.data)
      // console.log(JSON.parse(JSON.stringify(this.roleForm)))
      // console.log(this.$refs.tree)
      // 回填Tree
      this.$refs.tree.forEach((item, index) => {
        item.setCheckedKeys(this.roleForm.perms[index])
      })
    }
  }
}

</script>
<style scoped lang="scss">
.add-role {
  background-color: #f4f6f8;
  height: 100vh;
  overflow:hidden;

  .add-header {
    display: flex;
    justify-content: space-between;
    padding: 0 20px;
    height: 64px;
    line-height: 64px;
    font-size: 16px;
    font-weight: bold;
    background-color: #fff;

    .left {
      span {
        margin-right: 4px;
      }

      .arrow {
        cursor: pointer;
      }
    }

    .right {
      text-align: right;
    }
  }

  .add-main {
    position: absolute;
    top: 64px;
    bottom: 88px;
    width: 100%;
    overflow-y: auto;
    background: #f4f6f8;
    padding: 20px 230px;
    display: flex;
    .step-container {
      height: 400px;
      width: 200px;
    }
    .form-container {
      flex:1;
      background-color: #fff;
      overflow-y: auto;
      .title {
        height: 60px;
        line-height: 60px;
        padding-left: 20px;
      }
      .form {
        margin-bottom: 20px;
        padding: 20px 65px 24px;
        .el-form {
          display: flex;
          flex-wrap: wrap;
        }
        .info{
          font-size:14px;
          color:#666;
          .form-item{
            margin-bottom:20px;
          }
        }
      }
      .form-box{
        width: 600px;
        display: flex;
        flex-direction: column;
      }
    }
  }

  .add-footer {
    position: fixed;
    bottom: 0;
    width: 100%;
    padding: 24px 50px;
    color: #000000d9;
    font-size: 14px;
    background: #fff;
    text-align: center;
    z-index: 10001;
  }
  .tree-wrapper {
      display: flex;
      justify-content: space-between;
      flex-wrap: wrap;
      .tree-item {
        flex: 1;
        padding: 0px 4px;
        text-align: center;
        .tree-title {
          background: #f5f7fa;
          text-align: center;
          padding: 10px 0;
          margin-bottom: 12px;
        }
      }
    }
}
</style>
